package com.isoft.controller;

import com.isoft.result.R;
import com.isoft.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    /**
     * 获取验证码
     * @return 验证码图片和ID
     */
    @GetMapping("/captcha")
    public R getCaptcha() {
        try {
            Map<String, Object> captchaData = captchaService.generateCaptcha();
            return R.ok(captchaData);
        } catch (Exception e) {
            return R.error("生成验证码失败: " + e.getMessage());
        }
    }

    /**
     * 验证验证码
     * @param captchaId 验证码ID
     * @param captchaCode 验证码
     * @return 验证结果
     */
    @PostMapping("/captcha/validate")
    public R validateCaptcha(@RequestParam String captchaId,
                             @RequestParam String captchaCode) {
        try {
            boolean isValid = captchaService.validateCaptcha(captchaId, captchaCode);
            if (isValid) {
                return R.ok("验证码验证成功");
            } else {
                return R.error("验证码错误或已过期");
            }
        } catch (Exception e) {
            return R.error("验证码验证失败: " + e.getMessage());
        }
    }
}